package com.fj.netty.rpc.serializer;

import com.fj.netty.rpc.gson.ClassTypeAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author fj
 * @date 2024/1/17 17:28
 */
public enum Algorithm implements Serializer{
    JAVA{
        @Override
        public <T> byte[] serialize(T obj) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            try {
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
                objectOutputStream.writeObject(obj);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return byteArrayOutputStream.toByteArray();
        }

        @Override
        public <T> T deserialize(Class<T> clz, byte[] bytes) {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            try {
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
                return (T) objectInputStream.readObject();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    },
    JSON{

        final Gson GSON = new GsonBuilder().registerTypeAdapter(Class.class, new ClassTypeAdapter()).create();

        @Override
        public <T> byte[] serialize(T obj) {
            String json = GSON.toJson(obj);
            return json.getBytes(StandardCharsets.UTF_8);
        }

        @Override
        public <T> T deserialize(Class<T> clz, byte[] bytes) {
            return GSON.fromJson(new String(bytes,StandardCharsets.UTF_8),clz);
        }
    }
}
